<template>
  <div class="table-box">

    <h2 class="title">CRUD</h2>

    <div class="query-box">
      <el-input class="el-inp" v-model="inputQuery" placeholder="请搜索姓名" />
      <div>
        <el-button type="primary" @click="handleAdd('add')">
          增加
        </el-button>
        <el-button type="danger" @click="handleMultipleDelete()" v-if="batchDeleteList.length > 0">
          删除选中
        </el-button>
      </div>
    </div>

    <!-- 表格现在绑定到 filteredTableData -->
    <el-table border :data="filteredTableData" style="width: 100%" @selection-change="handleSelectionChange"
      ref="tableRef">

      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="email" label="邮箱" width="200" />
      <el-table-column prop="state" label="状态" width="120" />
      <el-table-column prop="address" label="地址" width="300" />
      <el-table-column fixed="right" label="操作" width="120" align="center">
        <template #default="scope">
          <el-button link type="primary" style="color: #E47470" size="small" @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button link type="primary" size="small" @click="handleEdit('edit', scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 增加和编辑的dialog -->
    <el-dialog v-model="dialogFormVisible" draggable width="40%">
      <template #header>
        {{ dialogTitle }}
      </template>
      <el-form :model="dialogForm">
        <el-form-item label="姓名">
          <el-input v-model="dialogForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="dialogForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="dialogForm.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="dialogForm.state" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="dialogForm.address" autocomplete="off" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogCancel">取消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确认</el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from "vue"; // 导入 computed

// ------------------- 数据 -------------------

const LOCAL_STORAGE_KEY = 'crud_table_data'; // 定义 localStorage 的键名

let inputQuery = ref(''); // 搜索框数据

// 初始默认数据，仅在 localStorage 中没有数据时使用
const defaultInitialTableData = [
  {
    id: 1,
    name: 'Tom1',
    state: 'California',
    phone: '13800138000',
    email: '13800138000@qq.com',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    id: 2,
    name: 'Tom2',
    state: 'California',
    phone: '13800138000',
    email: '13800138000@qq.com',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    id: 3,
    name: 'Tom3',
    state: 'California',
    phone: '13800138000',
    email: '13800138000@qq.com',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    id: 4,
    name: 'Tom4',
    state: 'California',
    phone: '13800138000',
    email: '13800138000@qq.com',
    address: 'No. 189, Grove St, Los Angeles',
  },
];

// allTableData 用于存储所有原始数据，它的变化会触发持久化
let allTableData = ref([]);
// tableData 变量不再需要，因为表格将绑定到 filteredTableData
// copyTableData 变量也不再需要，因为 allTableData 扮演了它的角色

let dialogFormVisible = ref(false);
let dialogType = ref('add');
let dialogTitle = ref('新增');
let dialogForm = reactive({});
let batchDeleteList = ref([]);

// ------------------- 选中元素 -------------------
const tableRef = ref(null);

// ------------------- 生命周期钩子 -------------------

onMounted(() => {
  // 在组件挂载时，尝试从 localStorage 中读取数据
  const storedData = localStorage.getItem(LOCAL_STORAGE_KEY);
  if (storedData) {
    try {
      // 解析 JSON 字符串并赋值给 allTableData
      const parsedData = JSON.parse(storedData);
      allTableData.value = parsedData;
    } catch (e) {
      console.error("Failed to parse data from localStorage:", e);
      // 如果解析失败，使用默认数据
      initializeWithDefaultData();
    }
  } else {
    // 如果 localStorage 中没有数据，则使用默认的初始数据
    initializeWithDefaultData();
  }
});

// 初始化数据到默认值并保存到 localStorage 的辅助函数
const initializeWithDefaultData = () => {
  allTableData.value = JSON.parse(JSON.stringify(defaultInitialTableData));
  saveDataToLocalStorage(); // 首次加载时也保存到 localStorage
};

// ------------------- 计算属性 -------------------

// filteredTableData 是实际显示在表格中的数据，它会根据 inputQuery 自动过滤 allTableData
const filteredTableData = computed(() => {
  if (!inputQuery.value) {
    // 如果搜索框为空，显示所有数据
    return allTableData.value;
  } else {
    // 根据搜索框内容过滤数据
    const query = inputQuery.value.toLowerCase();
    return allTableData.value.filter(item =>
      item.name.toLowerCase().includes(query)
    );
  }
});

// ------------------- 监听器 -------------------

// 深度监听 allTableData 的变化，并保存到 localStorage
// 只有 allTableData 的变化才触发持久化，搜索导致的 filteredTableData 变化不触发持久化
watch(allTableData, (newVal) => {
  saveDataToLocalStorage();
}, { deep: true });

// ------------------- 辅助函数 -------------------

// 将 allTableData 保存到 localStorage
const saveDataToLocalStorage = () => {
  localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(allTableData.value));
};


// ------------------- 方法 -------------------

// 表格多选
const handleSelectionChange = (rows) => {
  batchDeleteList.value = [];
  rows.forEach(item => {
    batchDeleteList.value.push(item.id);
  });
};

// 多选删除
const handleMultipleDelete = () => {
  const idsToDelete = new Set(batchDeleteList.value); // 使用 Set 提高查找效率
  // 过滤出未被删除的项，直接更新 allTableData
  allTableData.value = allTableData.value.filter(item => !idsToDelete.has(item.id));

  batchDeleteList.value = [];
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};

// 删除
const handleDelete = (row) => {
  // 直接更新 allTableData
  allTableData.value = allTableData.value.filter(item => item.id !== row.id);
};

// 编辑
const handleEdit = (type, row) => {
  dialogStateModify(type);
  // 深拷贝 row 到 dialogForm，避免直接修改 row 影响原始数据
  Object.assign(dialogForm, JSON.parse(JSON.stringify(row)));
};

// 增加
const handleAdd = (type) => {
  dialogStateModify(type);
  // 清空 dialogForm
  for (const key in dialogForm) {
    delete dialogForm[key];
  }
};

// 弹窗状态修改
const dialogStateModify = (type) => {
  dialogFormVisible.value = true;
  dialogType.value = type;
  if (dialogType.value === 'add') {
    dialogTitle.value = '新增';
  } else {
    dialogTitle.value = '编辑';
  }
};

// 弹窗取消
const handleDialogCancel = () => {
  dialogFormVisible.value = false;
};

// 弹窗确认
const handleDialogConfirm = () => {
  dialogFormVisible.value = false;

  if (dialogType.value === 'add') {
    // 生成新的唯一ID (确保是数字类型，与您的初始数据保持一致)
    const newId = allTableData.value.length > 0 ? Math.max(...allTableData.value.map(item => item.id)) + 1 : 1;
    const newItem = { id: newId, ...dialogForm };
    allTableData.value.push(newItem);
  } else if (dialogType.value === 'edit') {
    let index = allTableData.value.findIndex(item => dialogForm.id === item.id);
    if (index !== -1) {
      // 找到对应的原始数据项并更新
      Object.assign(allTableData.value[index], dialogForm);
    }
  }
  // allTableData 变化会触发 watch 监听和持久化
};

</script>

<style>
/* 样式部分保持不变 */
.table-box {
  width: 800px;
  margin: 200px auto;
}

.title {
  text-align: center;
}

.query-box {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-inp {
  width: 200px;
}
</style>